<template>
  <div class="app-container">
    <div class="front_edit">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <span style="font-size: 24px">合同明细</span>
        </el-col>
      </el-row>
    </div>
    <div>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-card class="box-card">
            <div slot="header" class="clearfix" style="display: flex;flex-wrap: nowrap;">
              <span>合同基本资料</span>
              <el-button
                style="margin-left: 10px"
                plain
                type="primary"
                size="small"
                v-show="false"
              >维护计费规则
              </el-button
              >
              <el-button
                type="primary"
                plain
                size="small"
                :disabled="saveCon"
                v-loading="saveLoad"
                @click="handleSaveCon('conDetailForm')"
              >保存合同
              </el-button>


            </div>

            <div style="height: 180px; overflow-y: auto">
              <el-form
                :model="conDetailForm"
                class="con_detail_form"
                :rules="rules"
                ref="conDetailForm"
                :inline="true"
                size="mini"
                label-position="right"
                label-width="95px"
              >
                <el-form-item label="外部对象" prop="customerGkeys">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="getCusNames(conDetailForm.customerGkeys)"
                    placement="top-start"
                  >
                    <el-select
                      v-model="conDetailForm.customerGkeys"
                      multiple
                      collapse-tags
                      filterable
                    >
                      <el-option
                        v-for="item in cusOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="合同代码" prop="conCode">
                  <el-input  v-model="conDetailForm.conCode"></el-input>
                </el-form-item>
                <el-form-item label="业务绑定" prop="conBusTypes">
                  <el-select
                    v-model="conDetailForm.conBusTypes"
                    collapse-tags
                    placeholder="请选择"
                    multiple
                  >
                      <el-option
                        v-for="item in logicsticsProcessOptions"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                      >
                      </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="经办人" prop="handleName">
                  <el-input  v-model="conDetailForm.handleName" @click.native="conHandleName=true"></el-input>
                </el-form-item>
                <div style="display: flex;flex-wrap: nowrap;">
                  <el-form-item label="开始时间" prop="conStartTime">
                    <el-date-picker
                      :disabled="this.conDetailForm.isCheck&&this.conDetailForm.isCheck==='1'"
                      v-model="conDetailForm.conStartTime"
                      value-format="yyyy-MM-dd"
                      type="date"
                      placeholder="选择日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="结束时间" prop="conEndTime">
                    <el-date-picker
                      :disabled="this.conDetailForm.isCheck&&this.conDetailForm.isCheck==='1'"
                      v-model="conDetailForm.conEndTime"
                      value-format="yyyy-MM-dd"
                      type="date"
                      placeholder="选择日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                <el-form-item label="码头" prop="companyCod">
                  <el-select
                    v-model="conDetailForm.companyCod"
                    collapse-tags
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in companyCodOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <!--<el-form-item label="通用合同" prop="isTemplate">-->
                  <!--<el-select v-model="conDetailForm.isTemplate">-->
                    <!--<el-option-->
                      <!--v-for="item in isTemplateOptions"-->
                      <!--:key="item.value"-->
                      <!--:label="item.label"-->
                      <!--:value="item.value">-->
                    <!--</el-option>-->
                  <!--</el-select>-->
                <!--</el-form-item>-->
                  <el-form-item label=优先级 prop="conPriority">
                    <el-input  v-model="conDetailForm.conPriority"></el-input>
                  </el-form-item>
                </div>
              </el-form>
              <el-form
                :model="conDetailForm"
                class="con_detail_form"
                :rules="rules"
                ref="conDetailForm"
                size="mini"
                label-position="right"
                label-width="95px"
              >
                <el-form-item label="备注" prop="remark">
                  <el-input type="textarea" style="width: 90%;" v-model="conDetailForm.remark"></el-input>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </el-col>

        <el-col :span="24">
          <div style="padding-top: 10px">
            <con-rules :cal-con-id="conId" v-if="conId != null"/>
          </div>
        </el-col>

      </el-row>

    </div>
  </div>
</template>

<script>
import {
  SprojectLabel,
  getCompanyCode,
  VCtmsClientLabel,
  getContractById,
  addContract,
  editContract,
  listConFile,
  deleteConFileByFileId,
  listConOperLog,
  getConFile,
  getConFileByFileId,
  contrastObj,
  editObjOut,
  updateConCode,
  updateAuthorizedToSign,
  oneKeyAddOutObjectsBatch,
  importLastApprover,
  importLastApproverCon
} from "@/api/contract/conbusiness";
import {
  listObjOut,
  listObjInner,
  delOutObj,
  delInnerObj,
  addOutObject,
  addInnerObject,
} from "@/api/contract/conobj";
import {getToken} from "../../../utils/auth";
import {getOaSession} from "@/api/system/user";
import {getInfo} from "@/api/login";
import ConRules from "@/views/contract/rules";


let Base64 = require('js-base64').Base64;

export default {
  components: {ConRules},
  props: {
    // 值
    value: [String, Object, Array],
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 10,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  name: "ConDetail",
  data() {
    var check = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          if (value < 18) {
            callback(new Error('必须年满18岁'));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    return {
      queryParams: {
        approvalName: ''
      },
      saveids: [],
      isTemplateOptions: [{label: '否', value: '0'}, {label: '是', value: '1'}],
      updateConCodeVisible: false,
      updateConCodeForm: {},
      approvalNameOptions: [],
      saveLoad: false,
      oaLoading: false,  //OA按钮加载动画
      isClearable: true, // 可清空（可选）
      isAccordion: true, // 可收起（可选）
      visibleOut: false, //新增外部对象弹出框
      visibleInner: false, //内部对象弹出框
      visiblePrintSign: false,
      conSignDialogVisible: false, //合同会签弹框
      conSignDialogVisibleauth: false, //授权签署弹窗
      conSignSealDialogVisible: false, //推送线上审批弹框
      openSpecial: false,
      putOaHandleSeal: false,
      currentContract: {},
      conStartTimeShowClass: false,
      conStartTimeChShowClass: false,
      conEndTimeShowClass: false,
      conEndTimeChShowClass: false,
      conHandleName:false,  //经办人弹窗
      signReportUrl: '',
      url: '/file/downloadFileto',
      props: {
        // 配置项（必选）
        value: "id",
        label: "label",
        children: "children",
        // disabled:true
      },
      defaultExpandedKey: [], //默认选中数组
      conDetailForm: {
        isTemplate: '0',
        isAdvpay: '0',
        handleDeptId: null,
        handleDeptName: "",
        conYear: null,
        conStartTimeCh: '0',
        conEndTimeCh: '365',
        conStartTimeSelect: 11,
        conEndTimeSelect: 21,
        partA: [],
        partB: [],
        partC: [],
        conPriority: 0
      },
      cusOptions: [],
      saveCon: false,
      putOaHandleCon: false,
      conSupplyOptions: [],
      conEffTypeOptions: [],
      conBusTypeOptions: [],
      conParentOptions: [],
      chargeUnitOptions: [],
      deptOptions: [],
      loading: false,
      logicsticsProcessOptions: [],
      companyCodOptions:[],
      isTypeOptions: [
        {value: "1", label: "是"},
        {value: "0", label: "否"},
      ],
      ConStartTimeOptions: [{value: 11, label: "固定日期"}, {value: 10, label: "动态日期"}],
      ConEndTimeOptions: [{value2: 21, label2: "固定日期"}, {value2: 20, label2: "动态日期"}],
      specialExpensesOptions: [
        {value: "船公司杂费", label: "船公司杂费"},
        {value: "行政规费", label: "行政规费"},
        {value: "铁路运费", label: "铁路运费"}
      ],
      treeDataValue: {},
      treeData: "",
      defaultProps: {
        children: "children",
        label: "label",
      },
      treeDataValueList: [],
      currentKey: null,
      rules: {
        conCode: [{required: true, message: "合同代码不能为空", trigger: "blur"}],
        conSupplyType: [
          {required: true, message: "支付类型", trigger: "blur"},
        ],
        conBusTypes: [
          {required: true, message: "请绑定业务类型", trigger: "blur"},
        ],
        companyCod: [
          {required: true, message: "请选择所属码头", trigger: "blur"},
        ],
        customerGkeys:[{required: true, message: "外部对象不能为空", trigger: "blur"}],
        handleName:[{required: true, message: "合同经办人不能为空", trigger: "blur"}],
        conEndTime:[{required: true, message: "合同开始时间不能为空", trigger: "blur"}],
        conStartTime:[{required: true, message: "合同结束时间不能为空", trigger: "blur"}]
      },
      fileList: [],
      uploadDialogVisible: false,
      uploadDialogTital: "",
      baseApi: "",
      uploadUrl: "",
      myHeaders: {}, //请求头内容
      objectOutList: [], //外部关系列表
      objectInnerList: [], //内部关系列表
      objectOutSelectList: [], //已勾选的外部关系
      objectInnerSelectList: [], //已勾选的内部关系
      addObjectOutList: [], //待增加的外部关系对象
      addObjectInnerList: [], //待增加的内部关系对象
      addObjectInnerValue: "", //待增加的内部关系显示文字
      conRateList: [],
      conFeeOptions: [], //合同费目下拉框
      conCurrencyOptions: [], //币种下拉框
      currentConRate: [], //选中的费率
      countersignList: [], //合同会签列表
      countersignSealList: [], //合同印章申请表
      deptName: "", //筛选部门
      userList: [], //人员列表
      queryUserParams: {}, //人员查询参数
      selectUserDataList: [], //人员选中列表
      currentRow: null,   //单选，当前行选中列表
      currentCheckNode: "", //当前选择节点id
      uploadFileType: "DRAFT", //上传文件类型
      rateSelectList: [], //费项选中数据
      deptCheckStrictly: true,
      OABaseUrl: "http://oatest.gzport.com/km/review/km_review_main/kmReviewMain.do?method=view&fdId=",  //OA流程界面,
      SSOUrl: "http://oatest.gzport.com/oa/api/auth/login_by_sso?sso=customer_sso&loginName=",                        //OA单点登录URL
      operLogList: [],  //日志数据
      sealOptions: [],    //印章类型
      sealSelected: [],
      sealNumber: 1,      //用章份数
      downloadUrl: '/file/downloadFile',
      sbsxOptions: [{label: '否', value: '0'}, {label: '是', value: '1'}],
      conId: null,
      CON: "CON",
      deptIds: [],
      payGets: [],
      iscontrastObj: true
    };
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
    // 列表
    list() {
      let temp = 1;
      if (this.value) {
        // 首先将值转为数组
        const list = Array.isArray(this.value) ? this.value : [this.value];
        // 然后将数组转为对象数组
        return list.map((item) => {
          if (typeof item === "string") {
            item = {name: item, url: item};
          }
          item.uid = item.uid || new Date().getTime() + temp++;
          return item;
        });
      } else {
        this.fileList = [];
        return [];
      }
    },
  },
  created() {
    this.baseApi = process.env.VUE_APP_BASE_API;
    const conId = this.$route.params && this.$route.params.conId;
    this.conId = this.$route.params && this.$route.params.conId;
    console.log(this.$route.params);
    this.getDicts("project_type").then((response) => {
      this.logicsticsProcessOptions = response.data;
    });
    getCompanyCode().then(res=>{
        this.companyCodOptions=res;
    })
//    SprojectLabel().then((response) => {
//       this.logicsticsProcessOptions = response;
//     });

    if (conId) {
      getContractById(conId).then((response) => {
        this.conDetailForm = response.data;
        this.treeDataValue.id = response.data.handleDeptId;
        this.initHandle();
        this.getContractObject(conId);
      });
      this.getConOperLog(conId);
    } else {
      getInfo().then(response => {
        this.conDetailForm.handleName = response.user.nickName;
        this.conDetailForm.handleDeptId = response.user.dept.deptId;
        // this.conDetailForm.conYearNumber = new Date().getFullYear()+"";
        this.$set(this.conDetailForm, 'conYearNumber', new Date().getFullYear() + "");
//        this.$set(this.conDetailForm, "dateRange", []);
//        this.conDetailForm.dateRange.push(this.parseTime(new Date(), '{y}-{m}-{d}'));
//        var endDate = new Date();
//        this.conDetailForm.dateRange.push(this.parseTime(endDate.setTime(endDate.getTime() + 3600 * 1000 * 24 * 365), '{y}-{m}-{d}'));
        this.initHandle();
      });
      this.getBusTypeAndLogProTo();
    }
    this.getCusList();
  },
  methods: {
    selectMemoryFn(val, row) { // 设置分页记忆二位数组方法
      // 注意：val 传过来默认为数组类型 ，row 为 Object（当前选择数据对象）
      let currentArr = this.selectUserDataList[this.currentPage - 1] // 当前分页对应数组
      if (!currentArr) {
        this.selectUserDataList[this.currentPage - 1] = val // 不存在这个二维数组，则创建这个二位数组
      } else { // 存在
        if (val.includes(row)) { // 选中
          this.selectUserDataList[this.currentPage - 1] = val
        } else { // 取消
          delete currentArr[currentArr.indexOf(row)]
        }
      }
    },
    selectMemoriedDataFn() { // 分页记忆自动选中方法
      let currentArr = this.selectUserDataList[this.currentPage - 1]  // 当前分页对应被选中数据
      if (currentArr && currentArr.length) { // 存在则继续执行
        let tempRowsIDs = this.userList.map(L => L.id) // 当前分页被选中数据的id集合
        currentArr.forEach((item, index) => { // 遍历当前分页被选中数据
          if (tempRowsIDs.includes(item.id)) { // id匹配上，则选中
            this.$refs.multipleTable.toggleRowSelection(this.userList[tempRowsIDs.indexOf(item.id)])
          }
        })
      }
    },
    getBusTypeAndLogProTo() {
    },
    ChangeSaler() {
      getBusTypeAndLogProSe(this.conDetailForm.conSupplyType).then(res => {
        this.logicsticsProcessOptions = res;
      })
    },
    cancel() {
      this.updateConCodeVisible = false;
      this.updateConCodeForm = {
        conCode: null
      };
    },
    updateContract() {
      this.saveLoad = true;
      editContract(this.conDetailForm).then((response) => {
        if (response && response.code === 200) {
          this.$modal.msgSuccess("修改成功");
          this.saveLoad = false;
          let conId = this.conDetailForm.conId
          getContractById(conId).then((response) => {
            this.conDetailForm = response.data;
            // let date = new Date();
            // date.setFullYear(response.data.conYear);
            // this.conDetailForm.conYear = date;
            let year = response.data.conYear + "";
            this.$set(this.conDetailForm, 'conYearNumber', year)
            this.treeDataValue.id = response.data.handleDeptId;
            // this.conDetailForm.handleDeptId = response.data.handleDeptId
            this.initHandle();
            this.getContractObject(conId);
          });
          this.getConOperLog(conId);
        }
        this.saveLoad = false;
      });
    },
    deletehandleUserSaveAuth() {
      //遍历数组得到每个id值，设置到idList里面
      this.conDetailForm.authorizedToSign = null;
      let query = {
        authorizedToSign: "",
        conId: this.conDetailForm.conId
      }
      updateAuthorizedToSign(query).then(res => {
        if (res.code === 200) {
          this.$modal.msgSuccess("保存授权签署人成功！");
        }
      })
      this.conSignDialogVisibleauth = false;
    },
    deleteHandleName(){
      //遍历数组得到每个id值，设置到idList里面
      this.conDetailForm.handleName=null;
      this.conHandleName=false;
    },
    saveHandleName(){
      if(this.currentRow.length==0){
        this.conHandleName=false;
      }else{
        //遍历数组得到每个id值，设置到idList里面
        for(var i=0;i<this.currentRow.length;i++){
          var obj=this.currentRow[i];
          this.conDetailForm.handleName=obj.userName;
        }
        this.conHandleName=false;
      }
    },

    //获取客户列表
    getCusList() {
      VCtmsClientLabel().then(res=>{
        this.cusOptions = res;
      })
    },

    //获取操作日志
    getConOperLog(conId) {
      listConOperLog(conId).then(response => {
        this.operLogList = response.data;
      })
    },

    getContractObject(conId) {
      listObjOut(conId).then((response) => {
        this.objectOutList = response.data;
      });
    },
    initHandle() {
    },
    recursionGet(setValues, valueId) {
      let value = null;
      for (let index = 0; index < setValues.length; index += 1) {
        if (setValues[index].id === valueId) {
          value = setValues[index].label;
          break;
        }
        if (
          setValues[index].children instanceof Array &&
          setValues[index].children.length > 0
        ) {
          const text = this.recursionGet(setValues[index].children, valueId);
          if (text) return text;
        }
      }
      return value;
    },

    // 初始化滚动条
    initScroll() {
      // 初始化显示
      this.$nextTick(() => {
        let scrollWrap = document.querySelectorAll(
          ".el-scrollbar .el-select-dropdown__wrap"
        )[0];
        let scrollBar = document.querySelectorAll(
          ".el-scrollbar .el-scrollbar__bar"
        );
        scrollWrap.style.cssText =
          "margin: 0px; max-height: none; overflow: hidden;";
        scrollBar.forEach((ele) => (ele.style.width = 0));
      });
    },
    // 清除选中
    clearHandle() {
      this.conDetailForm.handleDeptName = "";
      this.conDetailForm.handleDeptId = null;
      this.defaultExpandedKey = [];
      this.clearSelected();
    },
    /* 清空选中样式 */
    clearSelected() {
      let allNode = document.querySelectorAll("#tree-option .el-tree-node");
      allNode.forEach((element) => element.classList.remove("is-current"));
    },
    // 切换选项
    handleNodeClick(node) {
      console.log(node);
      console.log(this.props);
      this.conDetailForm.handleDeptName = node[this.props.label];
      this.conDetailForm.handleDeptId = node[this.props.value];
      this.defaultExpandedKey = [];
      if (!node.children || !node.children.length) {
        //补录选择完选项弹框不能收起
        this.$refs.treeSelect.blur();
      }
    },
    //选择部门
    handleDeptNodeClick(node) {
      this.queryUserParams.deptId = node.id;
      this.getUserList();
    },
    handleUserNameChange() {
      this.getUserList();
    },
    handleCommonUserName() {
      this.queryUserParams.deptId = null;
      this.queryUserParams.nickName = null;
      listCommonUser().then(response => {
        this.userList = response.data;
      })
    },
    handleSaveCon(formName) {
      if (this.saveLoad) {
        this.$modal.msgError("请勿重复提交");
        return;
      }
      if (this.conDetailForm.customerGkeys.length == 0) {
        this.$modal.msgError("请选择外部对象");
        return;
      }
      if (this.conDetailForm.conBusTypes.length == 0) {
        this.$modal.msgError("请选择业务绑定");
        return;
      }
      if (this.conDetailForm.companyCod== null) {
        this.$modal.msgError("请选择码头");
        return;
      }
      if (!this.conDetailForm.conCode) {
        this.$modal.msgError("请填写合同代码");
        return;
      }
      if (!this.conDetailForm.conStartTime) {
        this.$modal.msgError("请选择合同开始时间");
        return;
      }
      if (!this.conDetailForm.conEndTime) {
        this.$modal.msgError("请选择合同结束时间");
        return;
      }
      if(this.conDetailForm.conPriority<0){
        this.$modal.msgError("优先级请输入大于等于0的整数");
        return;
      }
          this.saveLoad = true;
          if (!this.conDetailForm.conId) {
            addContract(this.conDetailForm).then((response) => {
              if (response && response.code === 200) {
                this.$modal.msgSuccess("正在保存请稍等");
                this.$router.push({
                  path: "/con/condetail/data/" + response.data.conId,
                });
                this.saveLoad = false;
              }
              this.saveLoad = false;
            });
          } else {
            this.updateContract();
          }
    },
    amountCheck() {
      console.log(!this.conDetailForm.advpayAmount)
      if (this.conDetailForm.isAdvpay === '1' && (!this.conDetailForm.advpayAmount || !this.conDetailForm.advpayAmountType)) {
        return false;
      } else if (this.conDetailForm.isDeposit === '1' && (!this.conDetailForm.depositAmount || !this.conDetailForm.depositAmountType)) {
        return false;
      }
      if (this.conDetailForm.isAdvpay === '0') {
        this.conDetailForm.advpayAmount = 0;
      }
      if (this.conDetailForm.isDeposit === '0') {
        this.conDetailForm.depositAmount = 0;
      }
      return true;
    },
    conUploadHandle(fileType) {
      if (!this.conDetailForm.conId) {
        this.msgError("请先保存合同！");
        return;
      }
      this.fileList = [];
      this.uploadDialogVisible = true;
      this.getConFileList();
      var token = getToken();
      this.uploadUrl = this.baseApi;
      this.myHeaders = {Authorization: token};
      this.uploadUrl =
        this.baseApi +
        "/base/business/upload?conId=" +
        this.conDetailForm.conId +
        "&fileType=" +
        this.uploadFileType;
    },
    getCusNames(cusCodes) {
      let names = "";
      if(cusCodes!=undefined){
        cusCodes.forEach((cusCode) => {
          for (let i = 0; i < this.cusOptions.length; i++) {
            if (cusCode === this.cusOptions[i].value) {
              console.log("000"+names);
              names = names + this.cusOptions[i].label + ",";
            }
          }
        });
      }
      return names;
    },
    getConBusTypes12(cusCodes1) {
      let names = "";
      if(cusCodes1!=undefined){
        cusCodes1.forEach((cusCode1) => {
          for (let i = 0; i < this.logicsticsProcessOptions.length; i++) {
            if (cusCode1 === this.logicsticsProcessOptions[i].value) {
              names = names + this.logicsticsProcessOptions[i].label + ",";
            }
          }
        });
      }
      return names;
    },
    handleSelectionOutObjChange(val) {
      this.objectOutSelectList = val;
    },
    handleDelObjOut() {
      console.log(this.objectOutSelectList);
      delOutObj(this.objectOutSelectList).then((response) => {
        if (response.code === 200) {
          this.$modal.msgSuccess("删除成功！");
          this.getContractObject(this.conDetailForm.conId);
        }
      });
    },
    handleSelectionInnerObjChange(val) {
      this.objectInnerSelectList = val;
    },
    handleDelObjInner() {
      console.log(this.objectInnerSelectList);
      delInnerObj(this.objectInnerSelectList).then((response) => {
        if (response.code === 200) {
          this.$modal.msgSuccess("删除成功！");
          this.getContractObject(this.conDetailForm.conId);
        }
      });
    },
    ObjectSaveOrCel() {
      if (this.addObjectOutList.length > 0) {
        this.$confirm("是否新增内容？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.handleAddOutObject();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消",
            });
          });
      }
    },
    handleAddOutObject() {
      let data = {
        conId: this.conDetailForm.conId,
        cusIds: this.addObjectOutList,
      };
      addOutObject(data).then((response) => {
        if (response.code === 200) {
          this.addObjectOutList = [];
          this.visibleOut = false;
          this.getContractObject(this.conDetailForm.conId);
        }
      });
    },
    handleAddInnerObject() {
      let data = {
        conId: this.conDetailForm.conId,
        deptIds: this.addObjectInnerList,
      };
      addInnerObject(data).then((response) => {
        if (response.code === 200) {
          this.addObjectOutList = [];
          this.visibleInner = false;
          this.getContractObject(this.conDetailForm.conId);
        }
      });
    },
    rateTableCellStyle() {
      return "font-size:14px;padding:3px;";
    },
    conCurrencyFormat(data) {
      return this.selectDictLabel(this.conCurrencyOptions, data);
    },
    conChargeUnitFormat(data) {
      return this.selectDictLabel(this.chargeUnitOptions, data);
    },
    rateCurrentChange(row) {
      this.currentConRate = row;
    },
    /**编辑费项 */
    handleEditRate(row) {
      this.$set(row, "isEdit", true);
    },
    /**修改费项 */
    handleSaveRate() {
      for (let i = 0; i < editRateList.length; i++) {
        if (!editRateList[i].currency) {
          this.msgError("请输入币种");
          return;
        } else if (!editRateList[i].taxRate) {
          this.msgError("请输入税率");
          return;
        } else if (!editRateList[i].feeServiceId) {
          this.msgError("请输入费项");
          return;
        }
      }
      editConRate(editRateList).then((response) => {
        if (response.code === 200) {
          // for(let i=0;i<this.conRateList.length;i++){
          //   this.conRateList[i].isEdit = false;
          // }
          this.$modal.msgSuccess("保存成功");
        }
      });
    },

    /**修改费率列表删除空的数据 */
    removeEmptyRate() {
      for (let i = this.conRateList.length - 1; i >= 0; i--) {
        if (!this.conRateList[i].rateId) {
          this.conRateList.splice(i, 1);
        }
      }
    },

    /**费率选择改变 */
    handleRateSelectChange(val) {
      this.rateSelectList = val;
    },
    /**增加费项 */
    handleAddRate() {
      if (!this.conDetailForm.conId) {
        return this.msgError("请先保存合同再操作！");
      }
      let addRate = {
        isEdit: true,
        conId: this.conDetailForm.conId,
        taxRate: 0,
        enableTime: this.conDetailForm.dateRange,
        currency: 'CNY'
      };
      this.conRateList.push(addRate);
    },
    getUser(row) {
      let result = "";
      let nameList = row.nameList;
      nameList.forEach((name) => {
        result = result + ' ' + name;
      });
      return result;
    },
    getOpinion(row) {
    },
    //选择审批人
    handleSelectNames(row, column, cell, event) {
      if (column.property == "names") {
        this.conSignDialogVisible = true;
        this.getUserList();
        this.currentCheckNode = row.signId;
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    //获取人员
    getUserList() {
      if (this.queryUserParams.deptId || this.queryUserParams.nickName) {
        getUserInfo(this.queryUserParams).then((response) => {
          this.userList = response;
        });
      } else {
        listCommonUser().then(response => {
          this.userList = response.data;
        })
      }
    },

    //用户行点击
    rowUserHandClick(row, column, event) {
      this.$refs.userTable.toggleRowSelection(row);
    },

    //选择行改变
    handUserSelectionChange(selection) {
    },

    //选择行改变 单选
    handUserSelectionChangesingle(selection) {
      this.currentRow = selection;
    },
    //select框值改变时候触发的事件
    selectDeptChange(e) {
      var arrNew = [];
      var dataLength = this.mineStatusValue.length;
      var eleng = e.length;
      for (let i = 0; i < dataLength; i++) {
        for (let j = 0; j < eleng; j++) {
          if (e[j] === this.mineStatusValue[i].label) {
            arrNew.push(this.mineStatusValue[i]);
          }
        }
      }
      this.$refs.tree.setCheckedNodes(arrNew); //设置勾选的值
    },
    //跳转到OA系统
    toOAProject(flid) {
      if (!flid) {
        this.msgError("找不到流程id，请先推送或者刷新界面");
        return;
      }
      getOaSession().then(response => {
        if (response.code === 200) {
          console.log("登录")
          let username = localStorage.getItem("username");
          let url = this.OABaseUrl + flid;
          let encodeUrl = encodeURIComponent(url);
          let sso = this.SSOUrl + username + '&tickTime=' + response.tickTime + '&signature=' + response.data + '&next=' + escape(url);
          console.log(sso);
          window.open(sso);
        }
      })
    },

    //拼接操作记录
    getOperInfo(operLog) {
      let operInfo = operLog.title;
      if (operLog.operName) {
        operInfo = operInfo + " 操作人：" + operLog.nickName;
      }
      return operInfo;
    },
    //选择费项确定费率
    handleSelectFeeService(row) {
      for (let i = 0; i < this.conFeeOptions.length; i++) {
        if (this.conFeeOptions[i].id === row.feeServiceId) {
          row.taxRate = this.conFeeOptions[i].defaultTaxPoint;
          return;
        } else {
          row.taxRate = 0;
        }
      }
    }
    // isCheck(){
    //   if(this.conDetailForm&&this.conDetailForm.isCheck&&this.conDetailForm.isCheck==='1'){
    //     return true;
    //   }
    //   return false;
    // }
    ,
    handleReceiveUserInputOutObjectCusNameList(stringList) {

      let params = {
        conId: this.conId,
        cusNameList: stringList
      }
      oneKeyAddOutObjectsBatch(params).then(response => {
        if (response && response.code == 200) {

          // 刷新外部对象列表：重新获取objectOutList
          this.getContractObject(this.conId)

          // 提示：批量新增外部对象成功
          /**
           * {
           *     "msg": "操作成功",
           *     "code": 200,
           *     "failedCustomerNameList": [],
           *     "infoMap": {
           *         "sizeBeforeFilter": "3",
           *         "sizeAfterFilter": "3",
           *         "failedCount": "0",
           *         "successCount": "0",
           *         "alreadyExistCount": "3"
           *     }
           * }
           */


          // 提示：批量新增外部对象成功
          /**
           * 输入了sizeBeforeFilter个客户名，经过过滤后有sizeAfterFilter个客户名有效
           * 查询系统后，有alreadyExistCount个客户名已存在，新增successCount个客户名
           * （if failedCount>0）failedCount个客户名新增失败(查询不到公司信息)，失败的客户名有：failedCustomerNameList
           * 对已经存在/新增成功的客户，批量新增外部对象成功
           */

          let infoMap = response.infoMap
          let failedCustomerNameList = response.failedCustomerNameList
          let sizeBeforeFilter = infoMap.sizeBeforeFilter
          let sizeAfterFilter = infoMap.sizeAfterFilter
          let failedCount = infoMap.failedCount
          let successCount = infoMap.successCount
          let alreadyExistCount = infoMap.alreadyExistCount

          let message = `输入了${sizeBeforeFilter}个客户名，经过过滤后有${sizeAfterFilter}个客户名有效<br>`
          message += `查询系统后，有${alreadyExistCount}个客户名已存在，新增${successCount}个客户名<br>`
          if (failedCount > 0) {
            message += `${failedCount}个客户名新增失败(查询不到公司信息)，失败的客户名有：<br>`
            for (let i = 0; i < failedCustomerNameList.length; i++) {
              message += `${failedCustomerNameList[i]}<br>`
            }
          }
          message += `对已经存在/新增成功的客户，批量新增外部对象成功`

          this.$alert(message, '提示', {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true,
          });

        } else {
          this.$message({
            message: response.msg,
            type: 'error'
          })
        }


      })
    }
  },
  watch: {
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    userList(oldVal, newVal) { // 监听数据变化，然后执行分页记忆自动选中回调
      this.$nextTick(() => {
        this.selectMemoriedDataFn()
      })
    }
  }
};
</script>

<style scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  height: auto;
  max-height: 274px;
  overflow: hidden;
  overflow-y: auto;
}

.el-select-dropdown__item.selected {
  font-weight: normal;
}

ul li >>> .el-tree .el-tree-node__content {
  height: auto;
  padding: 0 20px;
}

.el-tree-node__label {
  font-weight: normal;
}

.el-tree >>> .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}

.el-tree >>> .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}

.selectInput {
  padding: 0 5px;
  box-sizing: border-box;
}

.el-tabs--border-card >>> .el-tabs__content {
  padding: 0px;
}
</style>

<style>

.check_name {
  cursor: pointer
}
</style>

<style lang="scss" scoped>
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  /*border: 1px solid #e4e7ed;*/
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

.save_buttonto1 {
  font-size: 24px;
}

.front_edit {
  .save_button {
    font-size: 24px;
  }
}

.con_detail_form .el-form-item--mini.el-form-item {
  margin-bottom: 5px;

  div {
    width: 250px;

    ::v-deep .el-input {
      width: 100% !important;
    }
  }

}

.el-tabs__content {
  padding: 2px;
}

.sign_button {
  margin-top: 5px;
  margin-bottom: 5px;
}
</style>
